﻿// The binders sets and gets specific values from data (It knows how to set and get specific values from data)
define([
    'Xjs/core/util'
],
function (util) {
    'use strict';

    console.log('Entering binder module');

    // Creates a function that sets the data with the given value
    var createSetter = function (name) {
        var names = name.split('.'),
        length = names.length,
        script = '';

        if (length == 1) {
            script += "data['" + names[0] + "'] = value;";
        }
        else {
            script = 'var d = data;';
            for (var i = 0; i < length - 1; ++i) {
                var n = names[i];
                script += "if (typeof d['" + n + "'] == 'undefined') {\n\r";
                script += "d['" + n + "'] = {};\n\r";
                script += "}\n\r";
                script += "d = d['" + n + "'];\n\r";
            }
            script += "d['" + names[i] + "'] = value;";
        }

        console.log(script);

        return new Function('data', 'value', script);
    };

    // Creates a function that returns the value of the field
    var createGetter = function (name) {
        var script = 'return data';

        name.split('.').forEach(function (n) {
            script += "['" + n + "']";
        });
        script += ';';

        console.log(script);

        return new Function('data', script);
    };

    return {

        create: function (conf) {
            var binder = {};
            if (util.isString(conf)) { // If the configuration contains the name of the accessor then create the getters and setters
                binder.set = createSetter(conf);
                binder.get = createGetter(conf);
            }
            else {
                binder.set = conf.set;
                binder.get = conf.get;
            }

            return binder;
        }
    };

});